package edu.ivanov.apm.tests;

import edu.ivanov.apm.ui.DrawBoard;
import edu.ivanov.apm.chaos.Turtle;
import edu.ivanov.apm.ui.PaintingTurtle;
import edu.ivanov.apm.ui.UI;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.util.Duration;

/**
 * User: ilya
 * Date: 11.10.13
 * Time: 22:51
 */
public class TestAnimation extends DrawBoard {

    public void draw() {
        final PaintingTurtle turtle = new PaintingTurtle(addCanvas());
        turtle.rotate(Math.PI / 4);
        turtle.jump(20);
        turtle.rotate(-Math.PI / 4);

        final Timeline timeline = new Timeline();
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.setAutoReverse(true);

        DoubleProperty distance = new SimpleDoubleProperty();
        distance.addListener(new ChangeListener<Number>() {

            private boolean growth = true;
            private int cycleNumber = 1;

            public void changed(ObservableValue<? extends Number> observableValue, Number number, Number number2) {
                double ds = number2.doubleValue() - number.doubleValue();
                boolean nowGrowth = ds > 0;
                if (nowGrowth != growth) {
                    cycleNumber++;

                    if (cycleNumber > 4) {
                        timeline.stop();
                        return;
                    }

                    growth = nowGrowth;
                    turtle.rotate(Math.PI / 2);
                }

                turtle.go(Math.abs(ds));
            }
        });

        KeyValue keyValue = new KeyValue(distance, 170);
        KeyFrame keyFrame = new KeyFrame(Duration.seconds(2), keyValue);

        timeline.getKeyFrames().add(keyFrame);
        timeline.play();
    }

    public static void main(String[] args) {
        UI.show(new TestAnimation());
    }
}
